package com.hainatong.jcmvvmbase.api;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.JsonParseException;
import com.hainatong.jcmvvmbase.repository.BaseRepository;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.json.JSONException;
import retrofit2.HttpException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

public abstract class BaseObserver<T> implements Observer<T>
{
    private static String TAG = "BaseObserver";

    protected BaseRepository repository;

    public BaseObserver( BaseRepository baseRepository )
    {
        this.repository = baseRepository;
    }

    @Override
    public void onSubscribe(Disposable d)
    {
        LogUtils.eTag( TAG ,"onSubscribe");
        repository.addDisposable( d );
        onStart();
    }


    protected void onStart()
    {

    }

    @Override
    public void onNext(T t)
    {
        LogUtils.eTag( TAG ,"onNext ");
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e)
    {
        String message;
        int code = -1;
        if (e instanceof UnknownHostException) {
            message = "没有网络";
        } else if (e instanceof HttpException) {
            message = "网络错误";
        } else if (e instanceof SocketTimeoutException) {
            message = "网络连接超时";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException) {
            message = "解析错误";
        } else if (e instanceof ConnectException) {
            message = "连接失败";
        }
        /*
        else if (e instanceof ServerException) {
            message = ((ServerException) e).message;
            code = ((ServerException) e).code;
        }
        */
        else {
            message = "未知错误";
        }
        ToastUtils.showShort(message);
        onError( code , message);
    }

    @Override
    public void onComplete()
    {
        LogUtils.eTag( TAG ,"onComplete ");
    }

    public abstract void onError( int code , String errorMsg);

    public abstract void onSuccess(T t);

}
